using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using DevCangjie.utils.Settings;
using DevCangjie.Pages.ConsolePage;
using Microsoft.UI.Xaml;
using System.IO;
namespace DevCangjie.utils.CommandRunner
{
    internal class CommandRunner
    {
        internal static void RunCommand(string command, string arguments)
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = command,
                    Arguments = arguments,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                using (Process process = new Process { StartInfo = startInfo })
                {
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    string error = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    // 输出结果
                    if (!string.IsNullOrEmpty(output))
                    {
                        Debug.WriteLine("Output: " + output);
                    }

                    if (!string.IsNullOrEmpty(error))
                    {
                        Debug.WriteLine("Error: " + error);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }
        }

        internal static string CompileCangjieSingleFile(string sourceFile, string outputFile)
        {
            // 构建编译指令
            string compiler = Settings.Settings.Instance.CangjiePath + "/bin/cjc.exe ";
            // 编译
            List<string> arguments = [
                $"{sourceFile}",
                $"-o {outputFile}"];

            String argument = string.Join(" ", arguments);
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = compiler,
                    Arguments = argument,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                using (Process process = new Process { StartInfo = startInfo })
                {
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    string error = process.StandardError.ReadToEnd();
                    process.WaitForExit();
                    // 输出结果
                    if (!string.IsNullOrEmpty(output))
                    {
                        ConsolePage.Instance.AppendOutput("Output: " + output);
                        return output;
                    }
                    if (!string.IsNullOrEmpty(error))
                    {
                        ConsolePage.Instance.AppendErrorOutput("Error: " + error);
                        return error;
                    }
                }
            }
            catch (Exception ex)
            {
                ConsolePage.Instance.AppendErrorOutput("Exception: " + ex.Message);
                return ex.Message;
            }
            return string.Empty;
        }

        internal static int RunProgram(string programPath, string arguments)
        {
            try
            {
                string envSetupPath = Path.Combine(Settings.Settings.Instance.CangjiePath, "envsetup.bat");
                if (!File.Exists(envSetupPath))
                {
                    ConsolePage.Instance.AppendOutput($"找不到 envsetup.bat: {envSetupPath}");
                    return -404;
                }
                // Combine program path and arguments with pause
                string command = $"call \"{envSetupPath}\" && \"{programPath}\" {arguments} && pause && exit";

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/k \"{command}\"", // /k keeps the shell open after execution
                    UseShellExecute = true,          // Allows the OS to create the window
                    CreateNoWindow = false,          // Ensures a window is created
                    WindowStyle = ProcessWindowStyle.Normal,
                    WorkingDirectory = Path.GetDirectoryName(programPath) ?? Environment.CurrentDirectory
                };

                Process process = new Process
                {
                    StartInfo = startInfo,
                    EnableRaisingEvents = true
                };

                process.Exited += (sender, e) =>
                {
                    // Notify when the program has exited
                    ConsolePage.Instance.AppendOutput($"程序 \"{programPath}\" 已退出。");

                };

                process.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
                ConsolePage.Instance.AppendOutput($"启动程序失败: {ex.Message}");
                return -1;
            }
            return 0;
        }

        internal static async Task<bool> CompileCangjieSingleFileAsync(string filePath, string v)
        {
            try
            {
                string result = await Task.Run(() => CompileCangjieSingleFile(filePath, v));
                return string.IsNullOrEmpty(result);
            }
            catch (Exception ex)
            {
                ConsolePage.Instance.AppendOutput($"编译失败: {ex.Message}");
                return false;
            }
        }

    }
}
